import pymysql
import traceback
"""db = pymysql.connect(user='root',password='123456',host='114.215.252.110',database='jqd',cursorclass = pymysql.cursors.DictCursor)
cursor = db.cursor()"""

# 查询数控库内容
"""cursor.execute('select * from person')
result = cursor.fetchone()
print(result)"""


"""cursor.execute("insert into person(name,age,address,ssn) values('张三','18','沈阳','12345678998')")
db.commit()
cursor.execute('select * from person')
result = cursor.fetchone()
print(result)"""


class Db:
    def __init__(self,user,password,host,database):
        self.user = user
        self.password = password
        self.host = host
        self.database = database
    def connect(self):
        self.db = pymysql.connect(user = self.user,password= self.password,host=self.host,database=self.database,cursorclass = pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def search(self,type:int,sql):
        self.connect()
        result = None
        if type == 1:
            try:
                self.cursor.execute(sql)
                result = self.cursor.fetchone()
                self.close()
                return result
            except:
                self.db.rollback()
                traceback.print_exc()
                return result
        elif type == 2:
            try:
                self.cursor.execute(sql)
                result = self.cursor.fetchall()
                self.close()
                return result
            except:
                self.db.rollback() # 如果出现了异常，就回滚操作
                traceback.print_exc()
                return result




